package com.asimplefox.aasr;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;

/**
 * {
 * "refresh_token": "25.df8194d760efdcacf6fb9cfaa2ecf498.315360000.2046243970.282335-116137823",
 * "expires_in": 2592000,
 * "session_key": "9mzdXvamoutNljGJgaVPJ9tBpyy7XS0UGpnEeT0XpVQINSwSg8EnIIaIBIBztaieCc0+dFP5ENnMRxv7BhceN\/\/wy0pkJT0=",
 * "access_token": "24.e33227bbeca9f9a62564f5a5e4ee19f7.2592000.1733475970.282335-116137823",
 * "scope": "public audio_voice_assistant_get audio_tts_post brain_all_scope brain_enhanced_asr brain_speech_realtime brain_asr_async wise_adapt lebo_resource_base lightservice_public hetu_basic lightcms_map_poi kaidian_kaidian ApsMisTest_Test权限 vis-classify_flower lpq_开放 cop_helloScope ApsMis_fangdi_permission smartapp_snsapi_base smartapp_mapp_dev_manage iop_autocar oauth_tp_app smartapp_smart_game_openapi oauth_sessionkey smartapp_swanid_verify smartapp_opensource_openapi smartapp_opensource_recapi fake_face_detect_开放Scope vis-ocr_虚拟人物助理 idl-video_虚拟人物助理 smartapp_component smartapp_search_plugin avatar_video_test b2b_tp_openapi b2b_tp_openapi_online smartapp_gov_aladin_to_xcx",
 * "session_secret": "6ba2a35238bec37710e4729e068921b7"
 * }
 *
 * @author github.kloping
 */
@Component
public class BaiduAasrService {
    @Value("${baidu.client_id}")
    private String clientId;
    @Value("${baidu.client_secret}")
    private String clientSecret;

    private TokenInfo tokenInfo;

    private TokenInfo getTokenInfo() {
        if (tokenInfo != null && !tokenInfo.isTokenExpired()) {
            return tokenInfo;
        }
        try {
            Document doc0 = Jsoup.connect("https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials" +
                            "&client_id=" + clientId + "&client_secret=" + clientSecret).ignoreContentType(true)
                    .header("Content-Type", "application/json").get();
            String json = doc0.body().text();
            tokenInfo = JSON.parseObject(json, TokenInfo.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return tokenInfo;
    }

    public TaskId create(String url) {
        try {
            JSONObject data = new JSONObject();
            data.put("speech_url", url);
            data.put("format", "wav");
            data.put("pid", 80001);
            data.put("rate", 16000);
            Document doc0 = Jsoup.connect("https://aip.baidubce.com/rpc/2.0/aasr/v1/create?access_token="
                            + getTokenInfo().getAccessToken()).ignoreContentType(true)
                    .header("Content-Type", "application/json")
                    .requestBody(data.toJSONString()).post();
            String json = doc0.body().text();
            return JSON.parseObject(json, TaskId.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public TaskResult query(TaskId taskId) {
        try {
            JSONObject data = new JSONObject();
            data.put("task_ids", List.of(taskId.getTask_id()));
            Document doc0 = Jsoup.connect("https://aip.baidubce.com/rpc/2.0/aasr/v1/query?access_token="
                            + getTokenInfo().getAccessToken()).ignoreContentType(true)
                    .header("Content-Type", "application/json")
                    .requestBody(data.toJSONString()).post();
            String json = doc0.body().text();
            return JSON.parseObject(json, TaskResult.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public TaskResult query(String... ids) {
        try {
            JSONObject data = new JSONObject();
            data.put("task_ids", ids);
            Document doc0 = Jsoup.connect("https://aip.baidubce.com/rpc/2.0/aasr/v1/query?access_token="
                            + getTokenInfo().getAccessToken()).ignoreContentType(true)
                    .header("Content-Type", "application/json")
                    .requestBody(data.toJSONString()).post();
            String json = doc0.body().text();
            return JSON.parseObject(json, TaskResult.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
